#include "stdafx.h"
#include "PairVec.h"

CxPairVec::CxPairVec()
{}

CxPairVec::~CxPairVec()
{}

HRESULT CxPairVec::GetCount(LPINT pnCount)
{
    if (!pnCount)
    {
        return E_POINTER;
    }

    *pnCount = (INT)m_vecData.size();

    return S_OK;
}

HRESULT CxPairVec::GetName(INT nIndex, LPBSTR pbsName)
{
    if (!pbsName)
    {
        return E_POINTER;
    }

    *pbsName = NULL;

    if (nIndex >= (INT)m_vecData.size())
    {
        ATLASSERT(!L"index is overflow");
        return E_FAIL;
    }

    const VALUE& value = m_vecData[nIndex];

    *pbsName = (value.first).AllocSysString();

    return S_OK;
}

HRESULT CxPairVec::AddStr(BSTR bsName, BSTR bsValue)
{
    m_vecData.push_back(VALUE(CString(bsName), CComVariant(bsValue)));
    return S_OK;
}

HRESULT CxPairVec::GetStr(INT nIndex, LPBSTR pbsValue)
{
    if (!pbsValue)
    {
        return E_POINTER;
    }

    *pbsValue = NULL;

    if (nIndex >= (INT)m_vecData.size())
    {
        ATLASSERT(!L"index is overflow");
        return E_FAIL;
    }

    const VALUE& value = m_vecData[nIndex];

    const CComVariant& vtVar = value.second;

    if (VT_BSTR != vtVar.vt)
    {
        ATLASSERT(!L"type not match");
        return E_FAIL;
    }

    vtVar.CopyTo(pbsValue);

    return S_OK;
}

HRESULT CxPairVec::AddInterface(BSTR bsName, IUnknown* pUnknown)
{
    m_vecData.push_back(VALUE(CString(bsName), CComVariant(pUnknown)));
    return S_OK;
}

HRESULT CxPairVec::GetInterface(INT nIndex, REFIID riid, void** ppvValue)
{
    if (!ppvValue)
    {
        return E_POINTER;
    }

    *ppvValue = NULL;

    if (nIndex >= (INT)m_vecData.size())
    {
        ATLASSERT(!L"index is overflow");
        return E_FAIL;
    }

    const VALUE& value = m_vecData[nIndex];

    HRESULT hRet = E_FAIL;

    CComVariant vtVar = value.second;

    if (vtVar.vt != VT_UNKNOWN  && vtVar.vt != VT_DISPATCH)
    {
        ATLASSERT(!L"type not match");
    }
    else if (vtVar.punkVal)
    {
        hRet = vtVar.punkVal->QueryInterface(riid, ppvValue);
    }

    return hRet;
}